/**
 * 独立公共方法类
 * @author mo_yq5
 *
 */
package com.myframework.smhj.common.tool;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.List;

import javax.servlet.http.HttpServletResponse;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public abstract class CommonUtil {

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
	
	/**
	 * 随机返回指定长度的数字和字母组合的字符串
	 * @param length
	 * @return
	 */
	public static String randomLN(int length) {
		final int bound = hexDigits.length - 1;
		String str = "";
		for (int i = 0; i < length; i++) {
			int r = new Double(Math.random() * bound).intValue();
			str += hexDigits[r];
		}
		return str;
	}
	
	public static String randomCharStr(int length) {
		String charStr = "";
		for (int i = 0; i<length; i++) {
			char c = (char)(Math.random()*93 + 33);
			charStr += c;
		}
		return charStr;
	}
	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param byteP
	 *            字节数组
	 * @return 十六进制字串
	 */
	public static String byteArrayToHexString(byte[] byteP) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < byteP.length; i++) {
			resultSb.append(byteToHexString(byteP[i]));
		}
		return resultSb.toString();
	}

	/**
	 * 
	 * @param byteP
	 * @return
	 */
	public static String byteToHexString(byte byteP) {
		int n = byteP;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String byteArrayToBase64(byte[] bytes) {
		return new BASE64Encoder().encodeBuffer(bytes);
	}

	public static byte[] base64ToByteArray(String str) {
		byte[] bytes = null;
		try {
			bytes = new BASE64Decoder().decodeBuffer(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}
	
	public static int jashEncode(String str, int len)
	{
		int hash = 1315423911;
		int i = 0;
		byte[] input = str.getBytes();
		if(input.length<len){
			len = input.length;
		}
		for(i = 0; i < len; i++)
		{
			hash ^= ((hash << 5) + input[i] + (hash >> 2));
		}
		if(hash<0){
			hash+=Integer.MAX_VALUE+1;
		}
		return hash;
	}
	
	/**
	 * 编码转换
	 * 
	 * @param stringP
	 * @return
	 */
	public static String toChinese(String stringP) {
		String chinese = "";
		try {
			chinese = new String(stringP.trim().getBytes("ISO8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("在进行字符转码时抛出异常,内容如下:");
			e.printStackTrace();
		}
		return chinese;
	}

	/**
	 * MD5加密
	 * 
	 * @param stringP
	 * @return
	 */
	public static String md5Encode(String stringP) {
		String resultString = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(stringP.getBytes()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 截取指定长度的字符串，并以省略号结尾
	 * 
	 * @param stringP
	 * @param lenghtP
	 * @return
	 */
	public static String subStr(String stringP, int lenghtP) {
		if (stringP.length() > lenghtP)
			stringP = stringP.substring(0, lenghtP) + "....";
		return stringP;

	}

	/**
	 * 合并两个List对象，并返回合并结果
	 * 
	 * @param list0P
	 * @param list1P
	 * @return
	 */
	public static List<Object> mergerList(List<Object> list0P, List<Object> list1P) {
		List<Object> list = list0P;
		for (int i = 0; i < list1P.size(); i++) {
			list.add(list1P.get(i));

		}
		return list;
	}

	/**
	 * 返回List对象元素以指定字符串连接的字符串形式
	 * 
	 * @param listP
	 * @param joinStringP
	 * @return
	 */
	public static String listToString(List<Object> listP, String joinStringP) {
		List<Object> list = listP;
		String joinString = joinStringP;
		String string = "";
		for (int i = 0; i < list.size(); i++) {
			if (string != "") {
				string += joinString + list.get(i);
			} else {
				string = "" + list.get(i);
			}
		}
		return string;
	}

	/**
	 * 返回List对象元素以“,”连接的字符串形式
	 * 
	 * @param listP
	 * @return
	 */
	public static String listToString(List<Object> listP) {
		return listToString(listP, ",");
	}

	/**
	 * 字符过滤
	 * 
	 * @param bodyP
	 * @return
	 */
	public static String clearSpechar(String bodyP) {
		bodyP = bodyP.replaceAll("\r\n", "");
		bodyP = bodyP.replaceAll("\r", "");
		bodyP = bodyP.replaceAll("\n", "");
		bodyP = bodyP.replaceAll("'", "\"");
		return bodyP;
	}

	/**
	 * 过滤script
	 * 
	 * @param valueP
	 * @return
	 */
	public static String filterScript(String valueP) {
		valueP = valueP.replaceAll("iframe", "ｉｆｒａｍｅ");
		valueP = valueP.replaceAll("script", "ｓｃｒｉｐｔ");
		return valueP;
	}

	/**
	 * 过滤html
	 * 
	 * @param valueP
	 * @return
	 */
	public static String htmlEncode(String valueP) {
		valueP = valueP.replaceAll("&", "&amp;");
		valueP = valueP.replaceAll("'", "&#39;");
		valueP = valueP.replaceAll("&amp;amp;", "&amp;");
		valueP = valueP.replaceAll("&amp;quot;", "&quot;");
		valueP = valueP.replaceAll("\"", "&quot;");
		valueP = valueP.replaceAll("&amp;lt;", "&lt;");
		valueP = valueP.replaceAll("<", "&lt;");
		valueP = valueP.replaceAll("&amp;gt;", "&gt;");
		valueP = valueP.replaceAll(">", "&gt;");
		valueP = valueP.replaceAll("&amp;nbsp;", "&nbsp;");
		return valueP;
	}

	/**
	 * 清除HTML标记
	 * 
	 * @param valueP
	 * @return
	 */
	public static String clearHtml(String valueP) {
		valueP = valueP.replaceAll("<", "&lt;");
		valueP = valueP.replaceAll(">", "&gt;");
		return valueP;
	}
	
	public static void writeData(HttpServletResponse response, String fileUrl) throws Exception {
		if (null == response) {
			throw new NullPointerException("response is null");
		}
		if (null == fileUrl || fileUrl.isEmpty()) {
			throw new NullPointerException("remote file url is null");
		}
		OutputStream outp = null;
		byte[] b = new byte[1024];
		URL url = null;
		HttpURLConnection con = null;
		DataInputStream dis = null;
		try {
			url = new URL(fileUrl);
			con = (HttpURLConnection) url.openConnection();
			con.setUseCaches(true);
			con.setDoInput(true);
			con.setConnectTimeout(10000);
			con.setReadTimeout(30000);

			response.reset();
			response.addHeader("Accept-Ranges", "bytes");
			response.addHeader("Content-Length", "" + con.getContentLength());
			response.setContentType(con.getContentType());
			outp = response.getOutputStream();

			dis = new DataInputStream(con.getInputStream());
			int i = -1;
			while ((i = dis.read(b)) > 0) {
				outp.write(b, 0, i);
				outp.flush();
			}
		} finally {
			con.disconnect();
			dis.close();
		}
	}
	public static void main(String[] args) {
		try {
			String strTest = "123456";
			System.out.println(CommonUtil.md5Encode(strTest));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}
